package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.HttpRequest;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class RegisterGoogleCM {
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	/**
		 * 
		 */
	// String regId="";
	private Activity mActivity;
	GoogleCloudMessaging gcm;
	  static final String TAG = "GCMDemo";
	  /**
	     * Substitute you own sender ID here. This is the project number got
	     * 
	     */
	    String SENDER_ID = "202517753016";
	 public RegisterGoogleCM(Activity mActivity){
		 this.mActivity=mActivity;
	 }
	 public void registerGCM(){
		 if (checkPlayServices()) {
		    	Log.v("", "This device is  supported.");
		    	 gcm = GoogleCloudMessaging.getInstance(mActivity);
		    	 ApplicationConstants.RED_ID = getRegistrationId(mActivity);
		    	 if(ApplicationConstants.RED_ID.isEmpty()){
		                registerInBackground();
		    	 }
		            	
		    }
	 }

	/**
	 * getid
	 * 
	 * @param mContext2
	 * @return
	 */
	private String getRegistrationId(Context mContext) {
		final SharedPreferences prefs = getGCMPreferences(mContext);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.isEmpty()) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
				Integer.MIN_VALUE);
		int currentVersion = getAppVersion(mContext);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGCMPreferences(Context mContext) {
		return mContext.getSharedPreferences(
				RegisterGoogleCM.class.getSimpleName(), Context.MODE_PRIVATE);
	}

	/**
	 * register id
	 */
	private void registerInBackground() {
		new AsystaskGCM().execute();
	}

	/**
	 * check google play service
	 * 
	 * @return
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(mActivity);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, mActivity,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			}
			return false;
		}
		return true;
	}

	class AsystaskGCM extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String msg = "";
			try {
				if (gcm == null) {
					gcm = GoogleCloudMessaging.getInstance(mActivity);
				}
				ApplicationConstants.RED_ID = "243234";
				ApplicationConstants.RED_ID = gcm.register(SENDER_ID);//
				msg = "Device registered, registration ID="
						+ ApplicationConstants.RED_ID;

				// request server
				sendRegistrationIdToBackend();
				// Persist the regID - no need to register again.
				storeRegistrationId(mActivity, ApplicationConstants.RED_ID);
			} catch (Exception ex) {
				msg = "Error :" + ex.getMessage();
				// If there is an error, don't just keep trying to register.
				// Require the user to click a button again, or perform
				// exponential back-off.
			}
			return msg;
		}

		/**
		 * Stores the registration ID and app versionCode
		 */
		private void storeRegistrationId(Context context, String regId) {
			final SharedPreferences prefs = getGCMPreferences(context);
			int appVersion = getAppVersion(context);
			Log.i(TAG, "Saving regId on app version " + appVersion);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(PROPERTY_REG_ID, regId);
			editor.putInt(PROPERTY_APP_VERSION, appVersion);
			editor.commit();
		}

		/**
		 * Sends the registration ID
		 */
		private void sendRegistrationIdToBackend() {
			String url = ApplicationConstants.BASE_URL
					+ "gcmusers/register_gcm";
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			JSONObject json = new JSONObject();
			try {
				json.put("st_GcmId", ApplicationConstants.RED_ID);
				json.put("st_GcmType", "0");//
			} catch (JSONException e) {
				e.printStackTrace();
			}
			params.add(new BasicNameValuePair("data", json.toString()));

			HttpRequest http = new HttpRequest();
			Log.v("", params.toString());//
			http.makeServiceCall(url, HttpRequest.POST, params);

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

}
